//
//  MyPersonInfoVC.m
//  MyNewProject
//
//  Created by sun on 2019/1/29.
//  Copyright © 2019 sun. All rights reserved.
//

#import "MyPersonInfoVC.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "STConfig.h"
@interface MyPersonInfoVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, STPhotoKitDelegate,UIGestureRecognizerDelegate>
@property(nonatomic,strong)UITableView * myTalbleView;
@property(nonatomic,copy)NSString * myJianJiStr;
@property(nonatomic,strong)UIImage * myImage;
@property (nonatomic, strong) UITextField *textField;

@end

@implementation MyPersonInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navTitle = @"编辑信息";
    [self.view addSubview:self.myTalbleView];
    
}
-(UITableView*)myTalbleView
{

    if (_myTalbleView ==nil) {
        _myTalbleView =[[UITableView alloc] initWithFrame:CGRectMake(0,SKTopBar_Height ,SCREEN_WIDTH , SCREENH_HEIGHT-SKTopBar_Height) style:UITableViewStyleGrouped];
        _myTalbleView.dataSource = self;
        _myTalbleView.delegate = self;
        _myTalbleView.estimatedRowHeight = 0;
        _myTalbleView.estimatedSectionFooterHeight = 0;
        _myTalbleView.estimatedSectionHeaderHeight = 0;
        _myTalbleView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            
            _myTalbleView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            
        } else {
            
            self.automaticallyAdjustsScrollViewInsets = NO;
            
        }
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardDismiss:)];
        tapGesture.delegate = self;
        [_myTalbleView addGestureRecognizer:tapGesture];
    }
    return _myTalbleView;
}
-(void)keyboardDismiss:(UIGestureRecognizer*)gesture
{
    
    [self.view endEditing:YES];
    
}
#pragma mark -  UITableView 代理相关

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    if (!cell) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
    }
    
    for (id view in [cell.contentView subviews])
    {
        
        [view removeFromSuperview];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    UILabel * label = [UILabel new];
    label.textColor = SKColorWithHex(0x444444);
    label.font = SKFONT_Medium(15.0f);
    label.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:label];
    
    switch (indexPath.section) {
        case 0:
        {
            label.frame =  CGRectMake(25, 0, 200, 80);
            label.text = @"头像";
            
            UIImageView * headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 70 -15, 5, 70, 70)];
            headImageView.layer.masksToBounds = YES;
            headImageView.layer.cornerRadius = headImageView.height/2;

            headImageView.tag = 1111111111;
            if (self.myImage) {

                headImageView.image = self.myImage;

            }
            else
            {
                [headImageView sd_setImageWithURL:[NSURL URLWithString:SafeString([UserInfoSingleton shareInstance].userInfo.head_url)] placeholderImage:SKIMAGE_NAMED(@"DefaultHead")];

            }
            [cell.contentView addSubview:headImageView];
        }
            break;
        case 1:
        {
            label.frame =  CGRectMake(25, 0, 100, 60);

            label.text = @"用户名";
            NSString * totalAmtStr = SafeString([UserInfoSingleton shareInstance].userInfo.nickname);
            UIFont * font = SKFONT_Medium(15.0);
            UITextField * textField =[[UITextField alloc] initWithFrame:CGRectMake(label.right+15, label.top, SCREEN_WIDTH- (label.right+15 +20), label.height)];

            textField.textAlignment = NSTextAlignmentRight;

            textField.textColor = SKColorWithHex(0x444444);
            textField.font = font;
            NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName:SKColorWithHex(0x999999),
                                                                                                                     NSFontAttributeName:textField.font
                                                                                                                     }];
            textField.attributedPlaceholder = attrString;

            self.textField = textField;
            
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:textField];
           
            if (self.myJianJiStr.length==0) {
                if (!IsStrEmpty(totalAmtStr)) {
                    textField.text = totalAmtStr;
                    self.myJianJiStr =totalAmtStr;
                }
            }
            else
            {
                textField.text = self.myJianJiStr;
            }
            [cell.contentView addSubview:textField];
        }
            break;
        default:
            break;
    }
    return cell;
}
- (void)textFiledEditChanged:(id)notification{
    
    self.myJianJiStr = self.textField.text;
    NSLog(@"------%@--------",self.myJianJiStr);
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat  heightForRow = 0;
    switch (indexPath.section) {
        case 0:
        {
            heightForRow = 80;
        }
            break;
        case 1:
        {
            heightForRow = 60;

        }
            break;
            
        default:
            break;
    }
    return heightForRow;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        UIView  * bgView = [UIView new];
        bgView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200);
        UIFont * font = [UIFont systemFontOfSize:18];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(20, bgView.height -44 , SCREEN_WIDTH -20 *2 , 44);
        button.imageView.contentMode = UIViewContentModeScaleAspectFit;
        button.backgroundColor = SKColorWithHex(0xE33030);
        [button setTitle:@"保存" forState:UIControlStateNormal];
        button.titleLabel.font = font ;
        [button setTitleColor:SKColorWithHex(0xFFFFFF) forState:UIControlStateNormal];
        [button addTarget:self action:@selector(changeDeal:) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:button];
        return bgView;
    }
    return nil;
    
}
#pragma mark -- 保存
-(void)changeDeal:(UIButton *)sender
{
    [self.view endEditing:YES];
    NSString *uid = self.uid;
    NSString *loginKey = self.loginKey;
    SKWeakSelf;
    if (self.myImage) {
        NSData *data = UIImageJPEGRepresentation(self.myImage, 0.1);
        [YQNetworking uploadFileWithUrl:@"my/upUserInfo" parameters:@{@"uid":uid,@"loginKey":loginKey ,@"nickname":self.myJianJiStr} fileData:data type:@"file.jpg"  name:@"head_img" mimeType:@"image/jpeg" reloginRefreshBlock:^(id response) {
        } successBlock:^(id response) {
            NSLog(@"%@",response);
            if ([response[@"status"] isEqualToString:@"ok"]) {
                if (!IsStrEmpty(response[@"data"])) {
                    if (SKUserUserDefaults_Get(@"UserInfo"))
                    {
                        NSLog(@"%@",SKUserUserDefaults_Get(@"UserInfo"));
                        
                        NSDictionary * dic = SKUserUserDefaults_Get(@"UserInfo");
                        
                        NSMutableDictionary * newDic =[NSMutableDictionary dictionaryWithDictionary:dic];
                        if (!IsStrEmpty(response[@"data"])) {
                            newDic[@"head_url"] = response[@"data"];
                            
                        }
                         newDic[@"nickname"] = SafeString(self.textField.text);
                        
                        SKUserUserDefaults_Save(newDic, @"UserInfo");
                        
                        [UserInfoSingleton shareInstance].userInfo = [YPLoginUserInfo modelObjectWithDictionary:SKUserUserDefaults_Get(@"UserInfo")];
                    }
                    [weakSelf.view makeToast:@"修改成功" duration:1 position:CSToastPositionCenter];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
            }
            else {
                [weakSelf.view makeToast:@"修改失败" duration:1 position:CSToastPositionCenter];
            }
        } failBlock:^(NSError *error) {

        }];
    }
    else
    {

        if (IsStrEmpty(self.myJianJiStr)) {
            
            [self.view makeToast:@"名字不能为空" duration:1 position:CSToastPositionCenter];
            
        }
        [YQNetworking postWithUrl:@"my/upUserInfo" params:@{@"uid":uid,@"loginKey":loginKey,@"nickname":self.myJianJiStr,@"head_img":@""} reloginRefreshBlock:^(id response) {
            
        } successBlock:^(id response) {
            
            NSLog(@"%@",response);
            
            if ([response[@"status"] isEqualToString:@"ok"]) {
                
                if (SKUserUserDefaults_Get(@"UserInfo"))
                {
                    NSLog(@"%@",SKUserUserDefaults_Get(@"UserInfo"));
                    
                    NSDictionary * dic = SKUserUserDefaults_Get(@"UserInfo");
                    
                    NSMutableDictionary * newDic =[NSMutableDictionary dictionaryWithDictionary:dic];
                    
                    newDic[@"nickname"] = SafeString(self.textField.text);
                    
                    SKUserUserDefaults_Save(newDic, @"UserInfo");
                    
                    [UserInfoSingleton shareInstance].userInfo = [YPLoginUserInfo modelObjectWithDictionary:SKUserUserDefaults_Get(@"UserInfo")];
                }
                [weakSelf.view makeToast:@"修改成功" duration:1 position:CSToastPositionCenter];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }
            else {
                [weakSelf.view makeToast:@"修改失败" duration:1 position:CSToastPositionCenter];
            }
        } failBlock:^(NSError *error) {
            
        }];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) {
        return 200;
    }
    return CGFLOAT_MIN;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0: {
            [self editImageSelected];
        }
            break;
        case 1: {

        }
            break;
        default:
            break;
    }
    
}

#pragma mark - --- delegate 视图委托 ---

#pragma mark - 1.STPhotoKitDelegate的委托

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    self.myImage = resultImage;

    [self.myTalbleView reloadData];
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *vc = [[STPhotoKitController alloc] init];
        vc.delegate = self;
        vc.imageOriginal = imageOriginal;
        vc.sizeClip = CGSizeMake(MIN(self.view.width, self.view.height), MIN(self.view.width, self.view.height));
        [self presentViewController:vc animated:true completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){ }];
}

#pragma mark - --- event response 事件相应 ---
- (void)editImageSelected
{
    UIAlertController *alertController = [[UIAlertController alloc]init];
    UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }    }];

    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:action0];
    [alertController addAction:action1];
    [alertController addAction:action2];
    [self presentViewController:alertController animated:YES completion:nil];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([NSStringFromClass([touch.view class]) isEqual:@"UITableViewCellContentView"]) {
        return NO;

        }
    return YES;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
